#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define THREAD_COUNT 2
int g_bowl=1;
pthread_mutex_t g_lock;
pthread_cond_t g_cond_eat;
pthread_cond_t g_cond_make;


void* eat_start(void* arg){
  pthread_detach(pthread_self());
  while(1){
    pthread_mutex_lock(&g_lock);
    while(g_bowl<=0){
      pthread_cond_wait(&g_cond_eat,&g_lock);
    }
    printf("i am eat start,i eat %d\n",g_bowl--);
    pthread_mutex_unlock(&g_lock);

    pthread_cond_signal(&g_cond_make);
  }
  return NULL;
}

void* make_start(void* arg){
  pthread_detach(pthread_self());
  while(1){
    pthread_mutex_lock(&g_lock);
    while(g_bowl>0){
      pthread_cond_wait(&g_cond_make,&g_lock);
    }

    printf("i am make start, i make %d\n",++g_bowl);
    pthread_mutex_unlock(&g_lock);

    pthread_cond_signal(&g_cond_eat);
  }
  return NULL;
}

int main(){
  pthread_t tid;
  pthread_mutex_init(&g_lock,NULL);
  pthread_cond_init(&g_cond_eat,NULL);
  pthread_cond_init(&g_cond_make,NULL);

  pthread_t eat[THREAD_COUNT],make[THREAD_COUNT];
  for(int i=0;i<THREAD_COUNT;i++)
  {
    int ret= pthread_create(&eat[i],NULL,eat_start,NULL);                           
      if(ret<0){                                                                   
        return 0;                                                                  
      }                                                                            
                                                                                   
      ret=pthread_create(&make[i],NULL,make_start,NULL);                               
      if(ret<0){
        return 0; 
  }
  }

  while(1){
    sleep(1);
  }

  pthread_mutex_destroy(&g_lock);
  pthread_cond_destroy(&g_cond_eat);
  pthread_cond_destroy(&g_cond_make);
  return 0;
}
